﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using HellSkeletons.ViewModels;
using Kinect.Toolbox;
using Kinect.Toolbox.Collectors;
using Kinect.Toolbox.Providers;
using Kinect.Toolbox.UI;
using Microsoft.Practices.Unity;

namespace HellSkeletons.Controls
{
    /// <summary>
    /// Interaction logic for HeavenSekeleton.xaml
    /// </summary>
    public partial class HeavenSekeleton : UserControl
    {
        private SkeletonDisplayManager _skeletonDisplayManager;

        public HeavenSekeleton()
        {
            InitializeComponent();
            Loaded += OnLoaded;
            var framesCollector = new FramesCollector(); 
            framesCollector.FrameReady += (s, arg) => Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(OnFrameReady(arg)));
        
        }

        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {

            _skeletonDisplayManager = new SkeletonDisplayManager(kinectCanvas);
            if (IsHeaven)
            {

                _skeletonDisplayManager.HeadImage =
                    new BitmapImage(
                        new Uri(
                            "http://www.bamn-fit.com/img/pageImg/angel_head.png"));
            }
            else
            {
                _skeletonDisplayManager.HeadImage =
                    new BitmapImage(
                        new Uri(
                            "http://files.gamebanana.com/img/ico/sprays/skull_on_fire.png"));
            }
            
        }

        private Action OnFrameReady(FrameReadyEventArgs arg)
        {
            if (_skeletonDisplayManager == null)
            {
                return () => { };
            }
            var frameProvider = DependencyFactory.Container.Resolve<IFrameProvider>();
            if (IsHeaven && frameProvider is KinectFrameProvider)
            {
                return () => _skeletonDisplayManager.Draw(arg.Frame.Skeletons, false);
            }
            if (!IsHeaven && frameProvider is BinaryFilesFrameProvider)
            {
                return () => _skeletonDisplayManager.Draw(arg.Frame.Skeletons, false);
            }
            return () => { };
        }

        public bool IsHeaven { get; set; }
    }
}
